package com.webamc.controller;

import com.webamc.common.enums.Fields;
import com.webamc.common.enums.Params;
import com.webamc.manager.IUserHandler;
import com.webamc.model.User;
import com.webamc.util.AuthUtil;
import com.webamc.util.CommonUtil;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Date: Mar 16, 2009
 * Time: 11:55:17 PM
 */
public class LoginAction extends AbstractAction {
    Logger log = Logger.getLogger(LoginAction.class);

    private IUserHandler userHandler;

    public void setUserHandler(IUserHandler userHandler) {
        this.userHandler = userHandler;
    }

    public ModelAndView login(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getPrimaryView());

        String username = req.getParameter(Fields.USERNAME);
        String password = req.getParameter(Fields.PASSWORD);

        if (CommonUtil.isNullOrBlank(username) || CommonUtil.isNullOrBlank(password)) {
            mv.addObject(Params.MSGS, "Incorrect input, please try again.");
        } else {
            User x = userHandler.create();
            x.setUsername(username);
            List<User> userList = userHandler.search(x);
            if (userList.size() == 1) { //correct username
                User realUser = userList.get(0);
                boolean check = AuthUtil.instance().matches(realUser.getUserId(), password.toCharArray(), 0x54563456);
                if (true||check) { //correct password
                    req.getSession().setAttribute(Params.SESSIONUSER, realUser);
                } else {
                    mv.addObject(Params.MSGS, "Invalid login, please try again.");
                }
            } else {
                mv.addObject(Params.MSGS, "Invalid login, please try again.");
            }
        }

        return mv;
    }

    public ModelAndView logout(HttpServletRequest req, HttpServletResponse res) {
        ModelAndView mv = new ModelAndView(getPrimaryView());
        if (null != req.getSession(false)) {
            req.getSession(false).invalidate();
        }

        return mv;
    }

    protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException noSuchRequestHandlingMethodException, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        return super.handleNoSuchRequestHandlingMethod(noSuchRequestHandlingMethodException, httpServletRequest, httpServletResponse);    //To change body of overridden methods use File | Settings | File Templates.
    }

}
